const express = require("express");
const path = require("path");
const cookieParser = require("cookie-parser");
const cors = require("cors");
const session = require("express-session");

const studentRouter = require("../routers/api/student.js");
const classRouter = require("../routers/api/class.js");
const adminRouter = require("../routers/api/admin.js");
const bookRouter = require("../routers/api/book.js");

const app = express();
const port = 9527
app.listen(port, () => {
    console.log(`Server is running on port ${port}`);
});
//静态资源目录
const staticPath = path.join(__dirname, "../public");

// app.use(session({
//     secret: "keyboard cat",  //加密字符串  -->必须配置
//     name: "session_id", 
//     resave: false,   //强制保存
//     saveUninitialized: true,   //强制初始化
//     cookie: {   //cookie配置
//         maxAge: 1000 * 60 * 60 * 24 * 7   //7天--过期时间
//     }
// }))

//配置跨域-->手动写法
// app.use(require("../routers/corsMiddleware.js"))

//使用插件配置跨域
app.use(cors({
    origin: function (origin, callback) {
        if (!origin) {
            callback(null, "*")
            return
        }
        callback(null, origin)
    },
    credentials: true //允许携带cookie
}))

app.use(require("./apiloggerMle.js"))

// 静态资源中间件
app.use(express.static(staticPath))
//加入cookie-parser中间件
app.use(cookieParser())

app.use(require("./tokenMiddleware.js"))

//解析application/x-www-form-urlencoded格式的请求体
app.use(express.urlencoded({ extended: false }))
// 解析application/json格式的请求体
app.use(express.json())
//使用路由处理请求
app.use("/api/student", studentRouter)
// app.use("/api/class",classRouter)
app.use("/api/admin", adminRouter)
// app.use("/api/book",bookRouter)

app.use("/api/upload", require("../routers/api/upload.js"))
app.use("/api/download",require("../routers/api/download.js"))

app.use(require("./errorMiddleware.js"))
